package thread;

public class SyncDemo1 {
    static boolean success1;
    static boolean success2;
    public static void main(String[] args) {
        Bank bank = new Bank();
        int count = 1;
        while (true){
            Thread t1 = new Thread() {
                public void run() {
                    success1 = bank.getMoney(1000);
                }
            };
            Thread t2 = new Thread() {
                public void run() {
                    success2 = bank.getMoney(1000);
                }
            };
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            t1.start();
            t2.start();

            if (success1 && success2){
                System.out.println("两人都取钱成功");
                System.out.println("共尝试了"+count+"次");
                break;
            }else {
                bank.saveAccount(1000);
                count++;
                success1=false;
                success2=false;
            }
        }
    }
}
class Bank {
    private int account = 1000;
    public synchronized boolean getMoney(int money) {
        int account = getAccount();
        if (account >= money) {
            account -= money;
            Thread.yield();//让当前线程主动放弃时间片，并重新获取时间片（线程切换）
            saveAccount(account);
            return true;
        }
        return false;
    }

    public void saveAccount(int account) {
        this.account = account;
    }

    public int getAccount() {
        return account;
    }

}
